<!DOCTYPE html>
<html>
<head>
    {{template "header"}}
</head>
<body>
<script>
    let getColumns = function () {
        return [
            {
                view: "combo", name: "node_id", label: tr("radius","Node"),
                options: "/admin/node/options",
                css: "nborder-input",
            },
            {view: "text", name: "realname", label: tr("radius","Realname"), css: "nborder-input"},
            {view: "text", name: "username", label: tr("radius","Username"), validate: webix.rules.isNotEmpty, css: "nborder-input"},
            {view: "text", name: "password", label: tr("radius","Password"), validate: webix.rules.isNotEmpty, css: "nborder-input"},
            {
                view: "text",
                name: "ip_addr",
                label: tr("radius","IP address"),
                placeholder: tr("radius","Account static IP, priority is higher than address pool"),
                css: "nborder-input"
            },
            {
                view: "combo", name: "profile_id", label: tr("radius","Profile"), validate: webix.rules.isNotEmpty,
                options: "/admin/radius/profile/options",
                css: "nborder-input",
            },
            {
                cols: [
                    {
                        view: "datepicker",
                        name: "expire_time",
                        id: 'expire_time_datepicker',
                        label: tr("radius","Expire time"),
                        stringResult: true,
                        format: "%Y-%m-%d",
                        validate: webix.rules.isNotEmpty,
                        css: "nborder-input",
                        editable: true
                    },
                    {
                        view: "button",
                        value: "+ 3 mth",
                        width: "80",
                        click: () => {
                            let value = $$('expire_time_datepicker').getValue();
                            if (value) {
                                let date = new Date(value);
                                date.setMonth(date.getMonth() + 3);
                                $$('expire_time_datepicker').setValue(date);
                            }
                        }
                    },
                    {
                        view: "button",
                        value: "+ 1 yr",
                        width: "80",
                        click: () => {
                            let value = $$('expire_time_datepicker').getValue();
                            if (value) {
                                let date = new Date(value);
                                date.setFullYear(date.getFullYear() + 1);
                                $$('expire_time_datepicker').setValue(date);
                            }
                        }
                    }
                ]
            },
            {
                view: "radio",
                name: "status",
                label: gtr("Status"),
                value: "enabled",
                options: ["enabled", "disabled"],
                validate: webix.rules.isNotEmpty,
                css: "nborder-input"
            },
            {name: "remark", view: "codemirror-editor", mode: "markdown"},
        ]
    }


    let openDetail = function (item) {
        let winid = "radius.user.detail." + item.id
        wxui.openWindow({
            width: 720,
            height: 576,
            winid: winid,
            title: tr("radius","User detail"),
            body: {
                rows: [
                    {
                        view: "tabbar",
                        css: "main-tabs",
                        animate: false,
                        bottomOffset: 0,
                        optionWidth: 110,
                        height: 36,
                        align: 'left',
                        multiview: true,
                        value: "radius_user_detail_tab", // the initially selected tab
                        options: [
                            {"id": "radius_user_detail_tab", "value": tr("radius","Information")},
                            {"id": "radius_user_remark_tab", "value": tr("radius","Description")},]
                    },
                    {
                        cells: [
                            {
                                id: 'radius_user_detail_tab',
                                rows: [
                                    {
                                        view: "form",
                                        paddingX: 20,
                                        scroll: "auto",
                                        elementsConfig: {
                                            marginY: 0,
                                            labelWidth: 150,
                                        },
                                        css: "detail-form",
                                        url: '/admin/radius/users/get?id=' + item.id,
                                        elements: [
                                            {
                                                view: "text",
                                                name: "realname",
                                                label: tr("radius","Realname"),
                                                readonly: true,
                                                css: "nborder-input"
                                            },
                                            {
                                                view: "text",
                                                name: "username",
                                                label: tr("radius","Username"),
                                                readonly: true,
                                                css: "nborder-input"
                                            },
                                            {
                                                view: "text",
                                                name: "password",
                                                label: tr("radius","Password"),
                                                readonly: true,
                                                css: "nborder-input"
                                            },
                                            {
                                                view: "text",
                                                name: "ip_addr",
                                                label: tr("radius","IP address"),
                                                readonly: true,
                                                placeholder: tr("radius","Account static IP, priority is higher than address pool"),
                                                css: "nborder-input"
                                            },
                                            {
                                                cols: [
                                                    {
                                                        view: "combo", name: "profile_id", label: tr("radius","Profile"),
                                                        options: "/admin/radius/profile/options", readonly: true,
                                                        css: "nborder-input",
                                                    },
                                                ]
                                            },
                                            {
                                                cols: [
                                                    {
                                                        view: "text",
                                                        name: "active_num",
                                                        readonly: true,
                                                        label: tr("radius","Active num"),
                                                        css: "nborder-input"
                                                    },
                                                    {
                                                        view: "text",
                                                        name: "addr_pool",
                                                        readonly: true,
                                                        label: tr("radius","Addr pool"),
                                                        css: "nborder-input"
                                                    },
                                                ]
                                            },
                                            {
                                                cols: [
                                                    {
                                                        view: "text",
                                                        name: "up_rate",
                                                        readonly: true,
                                                        format:"1,111" ,
                                                        label: tr("radius","UpRate (kbps)"),
                                                        css: "nborder-input"
                                                    },
                                                    {
                                                        view: "text",
                                                        name: "down_rate",
                                                        readonly: true,
                                                        format:"1,111",
                                                        label: tr("radius","DownRate (kbps)"),
                                                        css: "nborder-input"
                                                    },
                                                ]
                                            },
                                            {
                                                view: "text",
                                                name: "expire_time",
                                                label: tr("radius","Expire time"),
                                                readonly: true,
                                                css: "nborder-input"
                                            },
                                            {
                                                view: "combo",
                                                name: "status",
                                                readonly: true,
                                                label: gtr("Status"),
                                                value: "enabled",
                                                options: ["enabled", "disabled"],
                                                validate: webix.rules.isNotEmpty,
                                                css: "nborder-input"
                                            },
                                        ],
                                    }
                                ]
                            },
                            {
                                id: "radius_user_remark_tab",
                                rows: [
                                    {name: "remark", readonly: true, view: "codemirror-editor", value: item.remark, mode: "markdown"},
                                ]
                            },
                        ]
                    }
                ]
            },
        }).show()
    }

    let batchUpdate = function (ids, cbk) {
        let winid = "radius.user.batchUpdate." + webix.uid()
        let formid = webix.uid().toString()
        wxui.openWindow({
            width: 720,
            height: 576,
            winid: winid,
            title: tr("radius","Account batch update"),
            body: {
                rows: [
                    {
                        id: formid,
                        view: "form",
                        scroll: true,
                        elementsConfig: {labelWidth: 100},
                        elements: [
                            {
                                rows: [
                                    {label: tr("radius","User List"), view: "label",},
                                    {
                                        view: "list",
                                        borderless: true,
                                        template: "<i class='mdi mdi-switch'></i> #value#",
                                        url: "/admin/radius/users/options?ids=" + ids,
                                    },
                                ]
                            },
                            {
                                view: "combo", name: "profile_id", label: tr("radius","Profile"),
                                options: "/admin/radius/profile/options",
                                css: "nborder-input",
                            },
                            {
                                view: "datepicker",
                                name: "expire_time",
                                id: 'expire_time_datepicker',
                                label: tr("radius","Expire time"),
                                stringResult: true,
                                format: "%Y-%m-%d",
                                validate: webix.rules.isNotEmpty,
                                css: "nborder-input",
                                editable: true
                            },
                            {
                                view: "combo",
                                name: "status",
                                label: tr("radius","Status"),
                                value: "enabled",
                                options: ["enabled", "disabled"],
                                validate: webix.rules.isNotEmpty,
                                css: "nborder-input"
                            },
                        ],
                    },
                    {
                        padding: 5,
                        cols: [{},
                            {
                                view: "button",
                                name: "submit",
                                type: "form",
                                value: tr("global", "Save"),
                                width: 120,
                                height: 36,
                                click: function () {
                                    if (!$$(formid).validate()) {
                                        webix.message({
                                            type: "error",
                                            text: tr("global", "Please fill in the valid data."),
                                            expire: 1000
                                        });
                                        return false;
                                    }
                                    webix.confirm({
                                        title: "Operation confirmation",
                                        ok: "Yes", cancel: "No",
                                        text: "This operation will update the account number in bulk. Confirm?",
                                        callback: function (ev) {
                                            if (ev) {
                                                let param = $$(formid).getValues();
                                                param.user_ids = ids
                                                webix.ajax().post("/admin/radius/users/batchupdate", param).then(function (result) {
                                                    let resp = result.json();
                                                    webix.message({type: resp.msgtype, text: resp.msg, expire: 5000});
                                                    if (resp.code === 0) {
                                                        $$(winid).close();
                                                        if (cbk)
                                                            cbk()
                                                    }
                                                })
                                            }
                                        }
                                    });
                                }
                            },
                            {
                                view: "button",
                                css: "webix_transparent",
                                icon: "mdi mdi-close",
                                width: 70,
                                label: tr("global", "Cancel"),
                                click: function () {
                                    $$(winid).close();
                                }
                            }
                        ]
                    }
                ]
            },
        }).show()
    }

    let deleteItem = function (ids, callback) {
        webix.confirm({
            title: gtr("Operation confirmation"),
            ok: "Yes", cancel: "No",
            text: "Confirm to delete? This operation is irreversible.",
            callback: function (ev) {
                if (ev) {
                    webix.ajax().get('/admin/radius/users/delete', {ids: ids}).then(function (result) {
                        let resp = result.json();
                        webix.message({type: resp.msgtype, text: resp.msg, expire: 2000});
                        if (callback)
                            callback()
                    }).fail(function (xhr) {
                        webix.message({type: 'error', text: "Delete Failure:" + xhr.statusText, expire: 2000});
                    });
                }
            }
        });
    }

    webix.ready(function () {
        let importUrl = '/admin/radius/users/import'
        let importAddUrl = '/admin/radius/users/importadd'
        let exportUrl = '/admin/radius/users/export'
        let tableid = webix.uid();
        let uploadid = webix.uid();
        let uploadidadd = webix.uid();
        let queryid = webix.uid()
        let reloadData = wxui.reloadDataFunc(tableid, "/admin/radius/users/query", queryid)
        wxui.initUploadApi(uploadid, importUrl, reloadData);
        wxui.initUploadApi(uploadidadd, importAddUrl, reloadData);
        webix.ui({
            css: "main-panel",
            padding: 7,
            rows: [
                wxui.getPageToolbar({
                    title: tr("radius", "RADIUS Account"),
                    icon: "mdi mdi-account",
                    elements: [
                        wxui.getPrimaryButton(tr("radius","Batch create"), 120, false, function () {
                            $$(uploadidadd).fileDialog({});
                        }),
                        wxui.getPrimaryButton(tr("radius","Batch update"), 120, false, function () {
                            let rows = wxui.getTableCheckedIds(tableid);
                            if (rows.length === 0) {
                                webix.message({type: 'error', text: "Please select one", expire: 1500});
                            } else {
                                batchUpdate(rows.join(","), reloadData);
                            }
                        }),
                        wxui.getPrimaryButton(gtr("Edit"), 90, false, function () {
                            let item = $$(tableid).getSelectedItem();
                            if (item) {
                                let vitem = webix.copy(item)
                                wxui.openFormWindow({
                                    width: 640,
                                    height: 720,
                                    elementsConfig: {labelWidth: 160},
                                    title: tr("radius", "Edit radius account"),
                                    data: vitem,
                                    post: "/admin/radius/users/update",
                                    callback: reloadData,
                                    elements: getColumns()
                                }).show();
                            } else {
                                webix.message({type: 'error', text: "Please select one", expire: 1500});
                            }
                        }),
                        wxui.getPrimaryButton(gtr("Clone"), 90, false, function () {
                            let item = $$(tableid).getSelectedItem();
                            if (item) {
                                let vitem = webix.copy(item)
                                vitem.id = ""
                                wxui.openFormWindow({
                                    width: 640,
                                    height: 720,
                                    title: tr("radius", "Clone radius account"),
                                    data: vitem,
                                    post: "/admin/radius/users/add",
                                    callback: reloadData,
                                    elements: getColumns()
                                }).show();
                            } else {
                                webix.message({type: 'error', text: "Please select one", expire: 1500});
                            }
                        }),
                        wxui.getPrimaryButton(gtr("Create"), 90, false, function () {
                            wxui.openFormWindow({
                                width: 640,
                                height: 720,
                                elementsConfig: {labelWidth: 160},
                                title: tr("radius", "Create radius account"),
                                post: "/admin/radius/users/add",
                                callback: reloadData,
                                elements: getColumns()
                            }).show();
                        }),
                        wxui.getDangerButton(gtr("Remove"), 90, false, function () {
                            let rows = wxui.getTableCheckedIds(tableid);
                            if (rows.length === 0) {
                                webix.message({type: 'error', text: "Please select one", expire: 1500});
                            } else {
                                deleteItem(rows.join(","), reloadData);
                            }
                        }),
                    ],
                }),
                wxui.getTableQueryCustomForm(queryid, [
                    {
                        rows: [
                            {
                                cols: [
                                    {
                                        view: "combo",
                                        name: "equal[profile_id]",
                                        options: "/admin/radius/profile/options",
                                        label: tr("radius", "Profile"),
                                        // labelWidth: 40,
                                    },
                                    {
                                        view: "combo",
                                        name: "equal[status]",
                                        label: gtr("Status"),
                                        // labelWidth: 40,
                                        options: ["enabled", "disabled"],
                                    },
                                    {
                                        view: "counter", name: "expire_days", label: tr("radius","expiration is less than (day)"), labelWidth: 240, width: 400,
                                    },
                                ]
                            },
                            {
                                cols: [
                                    {view: "search", id: "keyword", name: "keyword", placeholder: "keywords", width: 360},
                                    {
                                        view: "button",
                                        label: gtr("Query"),
                                        css: "webix_transparent",
                                        type: "icon",
                                        icon: "mdi mdi-search-web",
                                        borderless: true,
                                        width: 100,
                                        click: function () {
                                            reloadData()
                                        }
                                    },{}
                                ]
                            }
                        ]
                    }
                ]),
                wxui.getDatatable({
                    tableid: tableid,
                    url: '/admin/radius/users/query',
                    columns: [
                        {
                            id: "state",
                            header: {content: "masterCheckbox", css: "center"},
                            headermenu: false,
                            css: "center",width:45,
                            template: "{common.checkbox()}"
                        },
                        {
                            id: "username",
                            header: [tr("radius","Username")],
                            adjust: true,
                            sort: "server",
                            template: "<a class='do_detail' href='javascript:void(0)'>#username#</a>"
                        },
                        {
                            id: "realname",
                            header: [tr("radius","Realname")],
                            adjust: true,
                            sort: "server",
                        },
                        {
                            id: "profile_id",
                            options: "/admin/radius/profile/options",
                            header: [tr("radius","Profile")],
                            adjust: true,
                            sort: "server"
                        },
                        {id: "online_count", header: [tr("radius","Onlines")], sort: "server", adjust: true},
                        {id: "addr_pool", header: [tr("radius","Addr pool")], sort: "server", adjust: true},
                        {id: "active_num", header: [tr("radius","Active num")], adjust: true, sort: "server"},
                        {
                            id: "up_rate", header: [tr("radius","UpRate (Mbps)")], template: function (obj) {
                                return Number(obj.up_rate) / 1000
                            }, adjust: true, sort: "server",
                        },
                        {
                            id: "down_rate",
                            header: [tr("radius","DownRate (Mbps)")],
                            template: function (obj) {
                                return Number(obj.up_rate) / 1000
                            },
                            adjust: true,
                            sort: "server",
                        },
                        {
                            id: "status",
                            header: [gtr("Status")],
                            sort: "server",
                            adjust: true
                        },
                        {
                            id: "expire_time",
                            header: [tr("radius","Expire time")],
                            sort: "server",
                            adjust: true,
                            format: function (value) {
                                return value.substr(0, 10)
                            },
                        },
                        {
                            id: "created_at",
                            header: [gtr("Created")],
                            sort: "server",
                            hidden: true,
                            adjust: true,
                            format: function (value) {
                                return value.substr(0, 10)
                            },
                        },
                        {
                            id: "updated_at",
                            header: [gtr("Updated")],
                            sort: "server",
                            hidden: true,
                            adjust: true,
                            format: function (value) {
                                return value.substr(0, 10)
                            },
                        },
                        {
                            id: "last_online",
                            header: [tr("radius","LastOnline")],
                            sort: "server",
                            adjust: true,
                        },
                        {id: "remark", header: [gtr("Remark")], sort: "string", adjust: true},
                        // {header: {content: "headerMenu"}, headermenu: false, width: 35}
                    ],
                    leftSplit: 1,
                    pager: true,
                    on: {
                        onItemDblClick: function (id, e, node) {
                            openDetail(this.getItem(id))
                        }
                    },
                    onClick: {
                        do_detail: function (e, id) {
                            openDetail(this.getItem(id))
                        }
                    },
                }),
                wxui.getTableFooterBar({
                    tableid: tableid,
                    actions: [
                        wxui.getIconButton(gtr("Import"), 100, "import", false, function () {
                            $$(uploadid).fileDialog({});
                        }),
                        wxui.getIconButton(gtr("Export"), 100, "download", false, function () {
                            wxui.exportData(exportUrl, 'RadiusUsers.csv')
                        }),
                    ],
                    callback: reloadData
                }),
            ]
        })
    })
</script>
</body>
</html>